package com.itlong.cloud.controller.sdkV3.entrance;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.IotCloudEntranceStateDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudDeviceSDKDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKGetByDeviceUniqueDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKServerGetElevatorPageDTO;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.sdk.CloudEntranceSDKEntranceInfoVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.commons.ICloudEntranceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudEntranceSDKServiceClient;
import com.itlong.cloud.iottp.IIotServerServiceClient;
import com.itlong.cloud.project.app.IAppProjectServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <desc>
 *      云门禁SDK服务端云端对旺龙云端控制器
 * </desc>
 *
 * @createDate 2019/03/14
 */
@RestController
@RequestMapping("/sdkv3/cloud/entrance")
public class SDKCloudEntranceController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(SDKCloudEntranceController.class);

    @Autowired
    private ICloudEntranceSDKServiceClient iCloudEntranceSDKServiceClient;

    @Autowired
    ICloudEntranceServiceClient iCloudEntranceServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    IIotServerServiceClient iIotServerServiceClient;

    @Autowired
    private RedisService redisService;

    @Autowired
    IAppProjectServiceClient iAppProjectServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    /**
     * <desc>
     * 查询唯一标识
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/03/14
     */
    @UnAuthAccessRequired
    public Object getEntranceKey(CloudDeviceSDKDTO dto) throws Exception {
        CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
        //初始值为 登录为工程人员登录  获取项目下所有的设备
        Integer robotWhiteListAuthStatus=0;
        Integer robotDeviceAuthStatus=0;
        if (!"1".equals(dto.getRoleId())) {
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(dto.getProjectId(), dto.getAppId());
            robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
        }
        cloudElevatorSDKServerGetElevatorPageDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        cloudElevatorSDKServerGetElevatorPageDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
        cloudElevatorSDKServerGetElevatorPageDTO.setAppId(dto.getAppId());
        cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKServerGetElevatorPageDTO.setRoleId(dto.getRoleId());
        cloudElevatorSDKServerGetElevatorPageDTO.setDeviceType(3);
        cloudElevatorSDKServerGetElevatorPageDTO.setRobotId(robotWhiteListAuthStatus==0?"":dto.getRobotId());
        LOG.info("======getEntranceKey查询唯一标识============入参================>{}",cloudElevatorSDKServerGetElevatorPageDTO.toString());
        List<String> deviceArr = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
        LOG.info("======getEntranceKey查询唯一标识============出参================>{}",null == deviceArr ? "" : deviceArr.toString());

        return deviceArr;
    }

    /**
     * <desc>
     *      根据设备唯一码查询门禁信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/03/14
     */
    @UnAuthAccessRequired
    public Object getEntranceInfo(CloudDeviceSDKDTO dto) throws Exception {
        //初始值为 登录为工程人员登录  获取项目下所有的设备
        Integer robotWhiteListAuthStatus=0;
        Integer robotDeviceAuthStatus=0;
        if (!"1".equals(dto.getRoleId())) {
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(dto.getProjectId(), dto.getAppId());
            robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
        }
        CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(dto.getDeviceUnique());
        cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(dto.getRobotId());
        CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
        cloudElevatorSDKServerGetElevatorPageDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
        cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
        cloudElevatorSDKServerGetElevatorPageDTO.setRoleId(dto.getRoleId());
        cloudElevatorSDKServerGetElevatorPageDTO.setRobotId(robotWhiteListAuthStatus==0?"":dto.getRobotId());
        cloudElevatorSDKServerGetElevatorPageDTO.setDeviceType(3);

        cloudElevatorSDKServerGetElevatorPageDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        cloudElevatorSDKServerGetElevatorPageDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);

        dto.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
        dto.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
        Map<String, Object> authMap = iCloudEntranceSDKServiceClient.getDeveloperAuth(dto.getAppId(), dto.getProjectId());
        //机器人云门禁对接权限
        if (dto.getRoleId().equals(PropertyPublicRoleEnum.ROBOT_DEVELOPER.toString()) && "0".equals(authMap.get("robotEntrance").toString())){
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_NONE_CLOUD_ENTRANCE_AUTH_ERR.getErrorCode(),dto.getRequestId(), dto.getResponseTimestamp(),"");
        }
        List<String> deviceUniques = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
        if (deviceUniques == null || deviceUniques.isEmpty()) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
        }
        List<String> deviceUniqueParams = StringHandlerUtil.splitStringList(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique());
        for (String deviceUniqueParam : deviceUniqueParams) {
            if (!deviceUniques.contains(deviceUniqueParam)) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
            }
        }
        LOG.info("======getEntranceInfo根据设备唯一码查询门禁信息============入参================>{}",null==cloudElevatorSDKGetByDeviceUniqueDTO?"":cloudElevatorSDKGetByDeviceUniqueDTO.toString());
        List<CloudEntranceSDKEntranceInfoVO> deviceArr = iCloudEntranceSDKServiceClient.getEntranceInfo(cloudElevatorSDKGetByDeviceUniqueDTO);
        LOG.info("======getEntranceInfo根据设备唯一码查询门禁信息============出参================>{}",null == deviceArr ? "" : deviceArr.toString());

        return deviceArr;
    }

    /**
     * <desc>
     *      发送开门指令
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/03/14
     */
    @ResponseBody
    @RequestMapping("/netOpenDoor")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_OPEN_ENTRANCE_LOG_DESC)
    public Object netOpenDoor() throws Exception{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKGetByDeviceUniqueDTO.class, request);
            cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(request.getAttribute("appId").toString());
            cloudElevatorSDKGetByDeviceUniqueDTO.setAppSecret(request.getAttribute("appSecret").toString());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", cloudElevatorSDKGetByDeviceUniqueDTO.toString());
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ENTRANCE_TYPE_LOG_DESC);

            CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
            cloudElevatorSDKServerGetElevatorPageDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
            cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
            cloudElevatorSDKServerGetElevatorPageDTO.setRoleId(cloudElevatorSDKGetByDeviceUniqueDTO.getRoleId());
            cloudElevatorSDKServerGetElevatorPageDTO.setRobotId(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
            cloudElevatorSDKServerGetElevatorPageDTO.setDeviceType(3);

            //初始值为 登录为工程人员登录  获取项目下所有的设备
            Integer robotWhiteListAuthStatus=0;
            Integer robotDeviceAuthStatus=0;
            if (!"1".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getRoleId())) {
                Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId(), cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
                robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
                robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
            }
            cloudElevatorSDKServerGetElevatorPageDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
            cloudElevatorSDKServerGetElevatorPageDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);

            cloudElevatorSDKServerGetElevatorPageDTO.setRobotId(robotWhiteListAuthStatus==0?"":cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
            cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(robotWhiteListAuthStatus==0?"":cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
            LOG.info("======netOpenDoor发送开门指令============入参================>{}",null==cloudElevatorSDKServerGetElevatorPageDTO?"":cloudElevatorSDKServerGetElevatorPageDTO.toString());

            List<String> deviceUniques = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
            String responseTimestamp = new Date().getTime()+"";
            if (deviceUniques == null || deviceUniques.isEmpty()) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(),request.getAttribute("requestId").toString(),responseTimestamp,"");
            }
            if (!deviceUniques.contains(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique())) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(),request.getAttribute("requestId").toString(),responseTimestamp,"");
            }
            //查询项目远程开门配置是否为启用 关闭则直接返回
            Integer networkOpen = iAppProjectServiceClient.getNetworkOpenSetting(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
            if(DataStatusEnum.DELETE.getType()==networkOpen){
                return new SDKMessageVO(AppErrorCodeEnum.CLOUD_ENTRANCE_NETWORK_OPEN_IS_CLOSED.getErrorCode(),request.getAttribute("requestId").toString(),responseTimestamp,"");
            }
            if (StringUtils.isBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl()) || (!"1".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl()) &&
                    !"0".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl()))) {
                cloudElevatorSDKGetByDeviceUniqueDTO.setOpenCtrl("1");
            }
            if ("1".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl())) {//开门时
                if (StringUtils.isBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId()))
                {//非机器人开门
                    if (cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() != null &&
                            cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() > 0 && cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() < 300) {

                        cloudElevatorSDKGetByDeviceUniqueDTO.setTimeout(cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout());
                    }else {
                        cloudElevatorSDKGetByDeviceUniqueDTO.setTimeout(3);
                    }
                }else {
                    if (cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() == null ||
                            cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() < 0 || cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() > 300) {
                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_TIME_OUT_ERR.getErrorCode(),request.getAttribute("requestId").toString(),responseTimestamp,"");
                    }
                    if (redisService.get(RedisConstant.ROBOT_CLOUD_ENTRANCE_CHECK_CACHE_KEY+cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId()+
                            cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique()) != null){
                        return new SDKMessageVO(SDKErrorCodeEnum.SDK_ROBOT_CALL_ELEVATOR_BUSY_ERR.getErrorCode(),request.getAttribute("requestId").toString(),
                                responseTimestamp,"");
                    }
                }
            }else {
                    cloudElevatorSDKGetByDeviceUniqueDTO.setTimeout(1);
            }
            String deviceUnique = cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique();
            //查询门禁设备的iot账号及绑定的iot产品key
            Map<String,Object> entrance = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKey(deviceUnique);
            //获取门禁设备型号
            Integer entranceType = iAppDeviceServiceClient.getEntranceTypeInfo(deviceUnique);
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            if(entrance != null && entrance.get("deviceUnique") != null) {
                //判断当前设备是否在线，如不在线返回失败
                String isOnline = iIotServerServiceClient.batchGetDeviceState(entrance.get("productKey").toString(),entrance.get("deviceUnique").toString());
                if(isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))){
                    return new SDKMessageVO(AppErrorCodeEnum.CLOUD_ENTRANCE_OUT_LINE.getErrorCode(),request.getAttribute("requestId").toString(),responseTimestamp,"");
                }
                if (PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE.getType() == entranceType) {//联动器
                    iCloudEntranceServiceClient.wippenOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                            Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(),
                            cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl(), cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout().toString(), entrance.get("productKey").toString(),
                            cloudElevatorSDKGetByDeviceUniqueDTO.getAppId(), IotOpenDoorSourceEnum.ITLONG_SDK.getType().toString(),
                            cloudElevatorSDKGetByDeviceUniqueDTO.getDoorDirection(),cloudElevatorSDKGetByDeviceUniqueDTO.getFloor(),correlationId.getId(),cloudElevatorSDKGetByDeviceUniqueDTO.getRobotFlag(),cloudElevatorSDKGetByDeviceUniqueDTO.getFoolType());
                }else {
                    iCloudEntranceServiceClient.entranceOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                            Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(),
                            cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl(), cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout().toString(), entrance.get("productKey").toString(),
                            cloudElevatorSDKGetByDeviceUniqueDTO.getAppId(), "",cloudElevatorSDKGetByDeviceUniqueDTO.getRobotFlag());
                }
                //开门指令为机器人开门，并且机器人id不为空时，将此次开门指令添加进缓存
                if (StringUtils.isNotBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId()) && cloudElevatorSDKGetByDeviceUniqueDTO.getRobotFlag() == "1"){
                    redisService.set(RedisConstant.ROBOT_CLOUD_ENTRANCE_CHECK_CACHE_KEY+cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId()+
                                    cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique(),RedisConstant.ROBOT_CLOUD_ENTRANCE_CHECK_CACHE_TIME,
                            cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
                }
            }else{
                return new SDKMessageVO(AppErrorCodeEnum.CLOUD_ENTRANCE_EXISTS.getErrorCode(),request.getAttribute("requestId").toString(),responseTimestamp,"");
            }
            boolean isOpen = false;
            if ("1".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl())) {//开门时
                //判断门禁当前状态是否是开门，如果是开门则返回成功，否则返回失败
                int count = 0;
                while(count<10){
                    Thread.sleep(200);
                    IotCloudEntranceStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ENTRANCE_STATE_CACHE +
                            cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique()), IotCloudEntranceStateDTO.class);
                    if(dto != null && dto.getMsgCode() == 0){
                        isOpen = true;
                        break;
                    }
                    count++;
                }
            }else {
                isOpen = true;
            }
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("isOpen",isOpen+"");
            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data",new JSONObject(resultMap));//签名使用json格式内容进行
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),request.getAttribute("requestId").toString(),
                    responseTimestamp,Md5EncryptUtil.getSDKV2Md5(signMap,request.getAttribute("requestId").toString(),responseTimestamp, cloudElevatorSDKGetByDeviceUniqueDTO.getAppSecret()),resultMap);

        }catch (Exception e){
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云门禁_netOpenDoor】远程开门失败",e);
        }
    }

    /**
     * <desc>
     *      查询云门禁状态
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/04/03
     */
    @UnAuthAccessRequired
    public Object getEntranceStatus(CloudDeviceSDKDTO dto) throws Exception {
        //初始值为 登录为工程人员登录  获取项目下所有的设备
        Integer robotWhiteListAuthStatus=0;
        Integer robotDeviceAuthStatus=0;
        if (!"1".equals(dto.getRoleId())) {
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(dto.getProjectId(), dto.getAppId());
            robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
        }
        List<String> deviceUniqueParams = StringHandlerUtil.splitStringList(dto.getDeviceUnique());
        List<IotCloudEntranceStateDTO> list = new ArrayList<>();
        for(String deviceUnique : deviceUniqueParams){

            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
            cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
            cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
            cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(deviceUnique);
            cloudElevatorSDKGetByDeviceUniqueDTO.setRoleId(dto.getRoleId());
            cloudElevatorSDKGetByDeviceUniqueDTO.setRobotId(robotWhiteListAuthStatus==0?"":dto.getRobotId());

            CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
            cloudElevatorSDKServerGetElevatorPageDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
            cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
            cloudElevatorSDKServerGetElevatorPageDTO.setRoleId(cloudElevatorSDKGetByDeviceUniqueDTO.getRoleId());
            cloudElevatorSDKServerGetElevatorPageDTO.setRobotId(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId());
            cloudElevatorSDKServerGetElevatorPageDTO.setDeviceType(3);

            dto.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
            dto.setRobotDeviceAuthStatus(robotDeviceAuthStatus);

            cloudElevatorSDKServerGetElevatorPageDTO.setRobotWhiteListAuthStatus(dto.getRobotWhiteListAuthStatus());
            cloudElevatorSDKServerGetElevatorPageDTO.setRobotDeviceAuthStatus(dto.getRobotDeviceAuthStatus());
            LOG.info("======getEntranceStatus查询云门禁状态============入参================>{}",null==cloudElevatorSDKServerGetElevatorPageDTO?"":cloudElevatorSDKServerGetElevatorPageDTO.toString());

            List<String> deviceUniques = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
            if (deviceUniques == null || deviceUniques.isEmpty()) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
            }
            if (!deviceUniques.contains(deviceUnique)) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(),dto.getRequestId(),dto.getResponseTimestamp(),"");
            }
            IotCloudEntranceStateDTO entranceStatus;
            //查询门禁设备的iot账号及绑定的iot产品key
            Map<String, Object> entrance = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKey(deviceUnique);
            int count = 0;
            int flag = 0;//上报指令标记
            while (count < 10) {
                entranceStatus = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ENTRANCE_STATE_CACHE +
                        deviceUnique), IotCloudEntranceStateDTO.class);
                if (entranceStatus != null) {
                    //判断门禁是否在线
                    //判断当前设备是否在线，如不在线返回失败
                    String isOnline = iIotServerServiceClient.batchGetDeviceState(entrance.get("productKey").toString(),entrance.get("deviceUnique").toString());
                    if(isOnline!=null && isOnline.equals("ONLINE")) {
                        entranceStatus.setIsOnline("0");
                    }else{
                        entranceStatus.setIsOnline("1");
                    }
                    list.add(entranceStatus);
                    break;
                } else {
                    if (flag == 0) {//保证只发送一次
                        //如从缓存中读取不到电梯的信息触发iot发送电梯控制指令
                        iCloudEntranceServiceClient.entranceStatusCtrl("itlong", entrance.get("deviceUnique").toString(),
                                Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(), "300",
                                entrance.get("productKey").toString());
                        flag++;
                    }
                }
                count++;
                //Thread.sleep(500);
            }
        }
        Map<String, Object> signMap = new HashMap<>();
        signMap.put("data", JSON.toJSONString(list));
        LOG.info("======getEntranceStatus查询云门禁状态============出参================>{}",signMap.toString());
        return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                Md5EncryptUtil.getSDKV2Md5(signMap,dto.getRequestId(),dto.getResponseTimestamp(), dto.getAppSecret()), list);
    }

}
